package com.example.resourceSharingPlatform.config.security.jwt;

import com.example.resourceSharingPlatform.security_entity.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;


/**
 * JWT的service层，验证生成token
 */
@Service
public class JwtAuthService {

    // 此处注入的bean在SpringConfig中产生, 如果不在其中声明则注入AuthenticationManager报错
    @Autowired
    private AuthenticationManager authenticationManager;

    //对token操作的类JwtTokenUtils
    @Autowired
    private JwtTokenUtils jwtTokenUtils;

    /*
     * 登录认证换取JWT令牌
     *
     */
    
    public String login(String username, String password) {
        //用户验证
        Authentication authentication = null;
        try {
            /*
             * 该方法会调用UserDetailsServiceImpl.loadUserByUsername
             * UserDetailsServiceImpl.loadUserByUsername是通过用户名获取userDetails实体
             */
            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            authentication = authenticationManager.authenticate(usernamePasswordAuthenticationToken);
        } catch (Exception e) {
            throw new RuntimeException("用户名密码错误");
        }

        Users loginUser = (Users) authentication.getPrincipal();
        // 生成token
        return jwtTokenUtils.generateToken(loginUser);

    }

}
